#!/usr/bin/python
# coding:utf-8

from . import db
from . import constants
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash

# 查找好友时,分两次查询, 一次查找主动添加的好友, 一次查找被动添加的好友, 即可得到全部好友
tb_user_firends = db.Table(
    "info_user_firends",
    db.Column("firends_id", db.Integer, db.ForeignKey("info_user.id"), primary_key=True),  # 被动添加好友的ID
    db.Column("firended_id", db.Integer, db.ForeignKey("info_user.id"), primary_key=True)  # 主动添加好友的ID
)

# TODO 建立用户在线状态的逻辑, 新建字段还是使用redis待商榷
class User(db.Model):
    __tablename__ = "info_user"

    id = db.Column(db.Integer, primary_key=True)  # 用户编号
    nick_name = db.Column(db.String(32), unique=True, nullable=False)  # 用户昵称
    password_hash = db.Column(db.String(128), nullable=False)  # 加密的密码
    mobile = db.Column(db.String(11), unique=True, nullable=False)  # 手机号
    money = db.Column(db.Integer)  # 用户金币数量
    avatar_url = db.Column(db.String(256))  # 用户头像路径
    is_admin = db.Column(db.Boolean, default=False)  # 是否是管理员
    is_delete = db.Column(db.Boolean, default=False)  # 逻辑删除
    # room_id = db.Column(db.Integer, db.ForeignKey("play_room.id"), nullable=True)  # 游戏房间ID, 退出时需删除

    # 用户的好友,查找时,需分主被动查询两次
    firends = db.relationship(
        "User",
        secondary=tb_user_firends,
        primaryjoin=id == tb_user_firends.c.firended_id,
        secondaryjoin=id == tb_user_firends.c.firends_id,
        backref=db.backref("firended", lazy="dynamic"),
        lazy="dynamic"
    )

    @property
    def password(self):
        raise AttributeError("当前属性不可读")

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def to_dict(self):
        resp_dict = {
            "id": self.id,
            "nick_name": self.nick_name,
            "avatar_url": constants.QINIU_DOMIN_PREFIX + self.avatar_url,
            "mobile": self.mobile,
            "money": self.mobile,
        }
        return resp_dict


class PlayRoom(db.Model):  # 房间暂时存放在mysql, 是否可以放在redis还待斟酌
    __tablename__ = "play_room"

    id = db.Column(db.Integer, primary_key=True)  # 房间编号
    name = db.Column(db.String(32), unique=True, nullable=False)  # 房间名字
    owner_id = db.Column(db.Integer, db.ForeignKey("info_user.id"), nullable=False)  # 房主ID
    password_hash = db.Column(db.String(128), nullable=False)  # 加密的密码

    @property
    def password(self):
        raise AttributeError("当前属性不可读")

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def to_dict(self):
        resp_dict = {
            "id": self.id,
            "name": self.name,
            "owner_id": self.owner_id
        }
        return resp_dict
